package com.hunan.api.catv.mq.consumer;


import com.alibaba.druid.util.StringUtils;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.hunan.api.catv.mq.MqConstants;
import com.hunan.api.catv.service.biz.mix.MixRecommendBiz;
import com.hunan.api.catv.service.biz.news.NewsBiz;
import com.hunan.api.catv.utils.SpringBeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;


@Component
public class LocalCacheConsumer {

    public static Logger log = LoggerFactory.getLogger(LocalCacheConsumer.class);

    @Autowired
    NewsBiz newsBiz;

    @Autowired
    MixRecommendBiz mixRecommendBiz;

    /**
     * 刷新系统缓存
     * localCacheBeanNames: beanName?key;beanName?key;beanName?key
     *
     * @param localCacheBeanNames
     */
    @RabbitListener(bindings = @QueueBinding(value = @Queue(), exchange = @Exchange(value = MqConstants.local_cache_exchange, type = ExchangeTypes.FANOUT)))
    public void cacheFlush(String localCacheBeanNames) {
        log.info("[LocalCacheFlush-MQ: {} ]", localCacheBeanNames);
        try {
            String[] beanNames = localCacheBeanNames.split(";");
            for (String beanName : beanNames) {
                Object key = null;
                if (beanName.indexOf("?") > 0) {
                    key = beanName.substring(beanName.indexOf("?") + 1);
                    beanName = beanName.substring(0, beanName.indexOf("?"));
                }
                @SuppressWarnings("unchecked")
                LoadingCache<Object, ?> bean = SpringBeanUtils.getBean(beanName, LoadingCache.class);
                if (!ObjectUtils.isEmpty(key)) {
                    if (StringUtils.isNumber(String.valueOf(key))) {
                        key = Integer.valueOf(String.valueOf(key));
                    }
                    bean.invalidate(key);
                    bean.get(key);
                } else {
                    bean.invalidateAll();
                }
            }
        } catch (Exception e) {
            log.info("[LocalCacheFlush-MQ-Error:{}]", e);
        }
    }

    @RabbitListener(bindings = @QueueBinding(value = @Queue(), exchange = @Exchange(value = MqConstants.news_local_cache_exchange, type = ExchangeTypes.FANOUT)))
    public void newsFlush(Integer newsId) {
        try {
            newsBiz.flushNewsCache(newsId);
            mixRecommendBiz.flushNewsCache(newsId);
        } catch (Exception e) {
            log.info("[FlushNewCache-MQ-Error:{}]", e);
        }
    }
}
